package blogger

import "gitee.com/go-boot/boot-interfaces/ilogger"

// LoggerHooks 钩子函数
type LoggerHooks struct {
	hooks map[ilogger.LogLevel][]ilogger.IHookItem
}

func DefaultHooks() *LoggerHooks {
	return &LoggerHooks{
		hooks: make(map[ilogger.LogLevel][]ilogger.IHookItem),
	}
}

func (h *LoggerHooks) Len() int {
	return len(h.hooks)
}

func (h *LoggerHooks) Get(level ilogger.LogLevel) []ilogger.IHookItem {
	return h.hooks[level]
}

func (h *LoggerHooks) Add(hook ilogger.IHookItem) {
	for _, level := range hook.Levels() {
		h.hooks[level] = append(h.hooks[level], hook)
	}
}

func (h *LoggerHooks) Fire(level ilogger.LogLevel, entry ilogger.IEntry) error {
	for _, hook := range h.hooks[level] {
		if err := hook.Fire(entry); err != nil {
			return err
		}
	}
	return nil
}

func (h *LoggerHooks) Execute(entry ilogger.IEntry) error {
	for _, hook := range h.Get(entry.GetLevel()) {
		if err := hook.Fire(entry); err != nil {
			return err
		}
	}
	return nil
}
